"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  ArrowLeft,
  User,
  Edit,
  Save,
  Camera,
  Award,
  BookOpen,
  MessageSquare,
  Heart,
  Eye,
  Calendar,
  MapPin,
  Phone,
  Mail,
  Globe,
  Building2,
} from "lucide-react"

export default function ProfilePage() {
  const router = useRouter()
  const [isEditing, setIsEditing] = useState(false)
  const [activeTab, setActiveTab] = useState("overview")
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)

  // 用户信息状态
  const [userInfo, setUserInfo] = useState({
    name: "",
    title: "",
    company: "",
    location: "",
    email: "",
    phone: "",
    website: "",
    bio: "",
    industry: "",
    experience: "",
    interests: [],
  })

  // 模拟用户数据
  const userStats = {
    posts: 23,
    followers: 1234,
    following: 567,
    likes: 2890,
    views: 15420,
  }

  const achievements = [
    { title: "创业新星", description: "完成首次创业", date: "2023年12月", icon: Award },
    { title: "融资达人", description: "成功获得A轮融资", date: "2023年10月", icon: Award },
    { title: "社区贡献者", description: "发布10篇优质内容", date: "2023年11月", icon: BookOpen },
    { title: "人气作者", description: "获得1000个赞", date: "2023年9月", icon: Heart },
  ]

  const myPosts = [
    {
      id: 1,
      title: "AI创业的5个关键要素",
      summary: "分享我在AI创业过程中总结的经验",
      date: "2024年1月10日",
      views: 1234,
      likes: 89,
      comments: 23,
    },
    {
      id: 2,
      title: "如何在6个月内完成A轮融资",
      summary: "从BP制作到投资人对接的完整流程",
      date: "2024年1月5日",
      views: 2345,
      likes: 156,
      comments: 45,
    },
    {
      id: 3,
      title: "技术创业者的商业化思考",
      summary: "技术背景创业者如何平衡技术与商业",
      date: "2023年12月28日",
      views: 987,
      likes: 67,
      comments: 12,
    },
  ]

  const bookmarkedPosts = [
    {
      id: 1,
      title: "2024年创业趋势预测",
      author: "投资观察员",
      date: "2024年1月12日",
    },
    {
      id: 2,
      title: "SaaS产品的定价策略",
      author: "产品专家",
      date: "2024年1月8日",
    },
  ]

  // 检查用户登录状态并加载用户信息
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    const userData = JSON.parse(user)
    setCurrentUser(userData)
    
    // 加载用户信息，优先使用保存的profile数据，否则使用注册时的数据
    const savedProfile = localStorage.getItem(`profile_${userData.id}`)
    if (savedProfile) {
      setUserInfo(JSON.parse(savedProfile))
    } else {
      // 使用注册时的基本信息初始化profile
      setUserInfo({
        name: userData.name || '',
        title: '',
        company: userData.company || '',
        location: '',
        email: userData.email || '',
        phone: userData.phone || '',
        website: '',
        bio: '',
        industry: '',
        experience: '',
        interests: [] as string[],
      })
    }
    setIsLoading(false)
  }, [router])

  const handleSave = () => {
    if (!currentUser) return
    
    setIsEditing(false)
    // 保存用户profile信息到localStorage
    localStorage.setItem(`profile_${currentUser.id}`, JSON.stringify(userInfo))
    
    // 更新currentUser中的基本信息
    const updatedUser = {
      ...currentUser,
      name: userInfo.name,
      email: userInfo.email,
      company: userInfo.company,
      phone: userInfo.phone
    }
    localStorage.setItem('currentUser', JSON.stringify(updatedUser))
    setCurrentUser(updatedUser)
    
    // 同时更新registeredUsers中的数据
    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
    const userIndex = registeredUsers.findIndex((u: any) => u.id === currentUser.id)
    if (userIndex !== -1) {
      registeredUsers[userIndex] = { ...registeredUsers[userIndex], ...updatedUser }
      localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers))
    }
    
    alert('信息保存成功！')
    console.log("保存用户信息:", userInfo)
  }

  const handleInputChange = (field, value) => {
    setUserInfo((prev) => ({
      ...prev,
      [field]: value,
    }))
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">加载用户信息...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30">
      {/* 顶部导航 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/50 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" onClick={() => router.back()}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回
            </Button>
            <div className="flex items-center space-x-2">
              <User className="w-6 h-6 text-blue-600" />
              <h1 className="text-xl font-semibold text-slate-900">个人中心</h1>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* 左侧个人信息卡片 */}
          <div className="lg:col-span-1 space-y-6">
            <Card>
              <CardContent className="p-6">
                <div className="text-center mb-6">
                  <div className="relative inline-block">
                    <Avatar className="w-24 h-24 mx-auto mb-4">
                      <AvatarImage src="/placeholder.svg?height=96&width=96" />
                      <AvatarFallback className="text-2xl">{userInfo.name ? userInfo.name[0].toUpperCase() : currentUser?.name?.[0]?.toUpperCase() || 'U'}</AvatarFallback>
                    </Avatar>
                    <Button
                      size="sm"
                      variant="outline"
                      className="absolute -bottom-2 -right-2 rounded-full w-8 h-8 p-0 bg-transparent"
                    >
                      <Camera className="w-4 h-4" />
                    </Button>
                  </div>
                  <h2 className="text-xl font-semibold text-slate-900 mb-1">{userInfo.name}</h2>
                  <p className="text-slate-600 mb-2">{userInfo.title}</p>
                  <Badge variant="outline">{userInfo.industry}</Badge>
                </div>

                <div className="space-y-3 text-sm">
                  <div className="flex items-center space-x-2 text-slate-600">
                    <Building2 className="w-4 h-4" />
                    <span>{userInfo.company}</span>
                  </div>
                  <div className="flex items-center space-x-2 text-slate-600">
                    <MapPin className="w-4 h-4" />
                    <span>{userInfo.location}</span>
                  </div>
                  <div className="flex items-center space-x-2 text-slate-600">
                    <Mail className="w-4 h-4" />
                    <span>{userInfo.email}</span>
                  </div>
                  <div className="flex items-center space-x-2 text-slate-600">
                    <Phone className="w-4 h-4" />
                    <span>{userInfo.phone}</span>
                  </div>
                  <div className="flex items-center space-x-2 text-slate-600">
                    <Globe className="w-4 h-4" />
                    <span>{userInfo.website}</span>
                  </div>
                </div>

                <div className="mt-6 pt-6 border-t border-slate-200">
                  <div className="grid grid-cols-2 gap-4 text-center">
                    <div>
                      <div className="text-lg font-semibold text-slate-900">{userStats.posts}</div>
                      <div className="text-xs text-slate-600">发布</div>
                    </div>
                    <div>
                      <div className="text-lg font-semibold text-slate-900">{userStats.followers}</div>
                      <div className="text-xs text-slate-600">关注者</div>
                    </div>
                    <div>
                      <div className="text-lg font-semibold text-slate-900">{userStats.following}</div>
                      <div className="text-xs text-slate-600">关注中</div>
                    </div>
                    <div>
                      <div className="text-lg font-semibold text-slate-900">{userStats.likes}</div>
                      <div className="text-xs text-slate-600">获赞</div>
                    </div>
                  </div>
                </div>

                <Button
                  className="w-full mt-6"
                  variant={isEditing ? "default" : "outline"}
                  onClick={() => (isEditing ? handleSave() : setIsEditing(true))}
                >
                  {isEditing ? (
                    <>
                      <Save className="w-4 h-4 mr-2" />
                      保存
                    </>
                  ) : (
                    <>
                      <Edit className="w-4 h-4 mr-2" />
                      编辑资料
                    </>
                  )}
                </Button>
              </CardContent>
            </Card>

            {/* 兴趣标签 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">兴趣领域</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex flex-wrap gap-2">
                  {userInfo.interests.map((interest, index) => (
                    <Badge key={index} variant="secondary" className="text-xs">
                      {interest}
                    </Badge>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 右侧主要内容 */}
          <div className="lg:col-span-3">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
              <TabsList className="grid w-full grid-cols-4">
                <TabsTrigger value="overview">概览</TabsTrigger>
                <TabsTrigger value="posts">我的发布</TabsTrigger>
                <TabsTrigger value="bookmarks">收藏</TabsTrigger>
                <TabsTrigger value="settings">设置</TabsTrigger>
              </TabsList>

              <TabsContent value="overview" className="space-y-6 mt-6">
                {/* 个人简介 */}
                <Card>
                  <CardHeader>
                    <CardTitle>个人简介</CardTitle>
                  </CardHeader>
                  <CardContent>
                    {isEditing ? (
                      <Textarea
                        value={userInfo.bio}
                        onChange={(e) => handleInputChange("bio", e.target.value)}
                        className="min-h-[100px]"
                        placeholder="介绍一下你自己..."
                      />
                    ) : (
                      <p className="text-slate-700 leading-relaxed">{userInfo.bio}</p>
                    )}
                  </CardContent>
                </Card>

                {/* 成就徽章 */}
                <Card>
                  <CardHeader>
                    <CardTitle>成就徽章</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {achievements.map((achievement, index) => {
                        const Icon = achievement.icon
                        return (
                          <div key={index} className="flex items-center space-x-3 p-3 bg-slate-50 rounded-lg">
                            <div className="p-2 bg-blue-100 rounded-lg">
                              <Icon className="w-5 h-5 text-blue-600" />
                            </div>
                            <div className="flex-1">
                              <h4 className="font-medium text-slate-900">{achievement.title}</h4>
                              <p className="text-sm text-slate-600">{achievement.description}</p>
                              <p className="text-xs text-slate-500">{achievement.date}</p>
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  </CardContent>
                </Card>

                {/* 最近活动 */}
                <Card>
                  <CardHeader>
                    <CardTitle>最近活动</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="flex items-center space-x-3">
                        <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                        <span className="text-sm text-slate-700">发布了新文章《AI创业的5个关键要素》</span>
                        <span className="text-xs text-slate-500">2小时前</span>
                      </div>
                      <div className="flex items-center space-x-3">
                        <div className="w-2 h-2 bg-green-600 rounded-full"></div>
                        <span className="text-sm text-slate-700">参加了"创业者线下聚会"活动</span>
                        <span className="text-xs text-slate-500">1天前</span>
                      </div>
                      <div className="flex items-center space-x-3">
                        <div className="w-2 h-2 bg-purple-600 rounded-full"></div>
                        <span className="text-sm text-slate-700">收藏了文章《2024年创业趋势预测》</span>
                        <span className="text-xs text-slate-500">3天前</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="posts" className="space-y-6 mt-6">
                <div className="flex justify-between items-center">
                  <h3 className="text-lg font-semibold">我的发布 ({myPosts.length})</h3>
                  <Button>
                    <Edit className="w-4 h-4 mr-2" />
                    写文章
                  </Button>
                </div>

                <div className="space-y-4">
                  {myPosts.map((post) => (
                    <Card key={post.id}>
                      <CardContent className="p-6">
                        <div className="flex justify-between items-start mb-3">
                          <div className="flex-1">
                            <h4 className="font-semibold text-slate-900 mb-2">{post.title}</h4>
                            <p className="text-slate-600 text-sm mb-3">{post.summary}</p>
                            <div className="flex items-center space-x-4 text-xs text-slate-500">
                              <div className="flex items-center space-x-1">
                                <Calendar className="w-3 h-3" />
                                <span>{post.date}</span>
                              </div>
                              <div className="flex items-center space-x-1">
                                <Eye className="w-3 h-3" />
                                <span>{post.views}</span>
                              </div>
                              <div className="flex items-center space-x-1">
                                <Heart className="w-3 h-3" />
                                <span>{post.likes}</span>
                              </div>
                              <div className="flex items-center space-x-1">
                                <MessageSquare className="w-3 h-3" />
                                <span>{post.comments}</span>
                              </div>
                            </div>
                          </div>
                          <Button variant="ghost" size="sm">
                            <Edit className="w-4 h-4" />
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </TabsContent>

              <TabsContent value="bookmarks" className="space-y-6 mt-6">
                <div className="flex justify-between items-center">
                  <h3 className="text-lg font-semibold">我的收藏 ({bookmarkedPosts.length})</h3>
                </div>

                <div className="space-y-4">
                  {bookmarkedPosts.map((post) => (
                    <Card key={post.id}>
                      <CardContent className="p-6">
                        <div className="flex justify-between items-start">
                          <div className="flex-1">
                            <h4 className="font-semibold text-slate-900 mb-1">{post.title}</h4>
                            <div className="flex items-center space-x-2 text-sm text-slate-600">
                              <span>作者：{post.author}</span>
                              <span>·</span>
                              <span>{post.date}</span>
                            </div>
                          </div>
                          <Button variant="ghost" size="sm">
                            查看
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </TabsContent>

              <TabsContent value="settings" className="space-y-6 mt-6">
                <Card>
                  <CardHeader>
                    <CardTitle>基本信息</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="name">姓名</Label>
                        <Input
                          id="name"
                          value={userInfo.name}
                          onChange={(e) => handleInputChange("name", e.target.value)}
                        />
                      </div>
                      <div>
                        <Label htmlFor="title">职位/头衔</Label>
                        <Input
                          id="title"
                          value={userInfo.title}
                          onChange={(e) => handleInputChange("title", e.target.value)}
                        />
                      </div>
                      <div>
                        <Label htmlFor="company">公司</Label>
                        <Input
                          id="company"
                          value={userInfo.company}
                          onChange={(e) => handleInputChange("company", e.target.value)}
                        />
                      </div>
                      <div>
                        <Label htmlFor="location">所在地</Label>
                        <Input
                          id="location"
                          value={userInfo.location}
                          onChange={(e) => handleInputChange("location", e.target.value)}
                        />
                      </div>
                      <div>
                        <Label htmlFor="email">邮箱</Label>
                        <Input
                          id="email"
                          type="email"
                          value={userInfo.email}
                          onChange={(e) => handleInputChange("email", e.target.value)}
                        />
                      </div>
                      <div>
                        <Label htmlFor="phone">电话</Label>
                        <Input
                          id="phone"
                          value={userInfo.phone}
                          onChange={(e) => handleInputChange("phone", e.target.value)}
                        />
                      </div>
                      <div>
                        <Label htmlFor="website">个人网站</Label>
                        <Input
                          id="website"
                          value={userInfo.website}
                          onChange={(e) => handleInputChange("website", e.target.value)}
                        />
                      </div>
                      <div>
                        <Label htmlFor="industry">所属行业</Label>
                        <Select
                          value={userInfo.industry}
                          onValueChange={(value) => handleInputChange("industry", value)}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="互联网/科技">互联网/科技</SelectItem>
                            <SelectItem value="电子商务">电子商务</SelectItem>
                            <SelectItem value="教育培训">教育培训</SelectItem>
                            <SelectItem value="医疗健康">医疗健康</SelectItem>
                            <SelectItem value="金融服务">金融服务</SelectItem>
                            <SelectItem value="其他">其他</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <div>
                      <Label htmlFor="bio">个人简介</Label>
                      <Textarea
                        id="bio"
                        value={userInfo.bio}
                        onChange={(e) => handleInputChange("bio", e.target.value)}
                        className="min-h-[100px]"
                      />
                    </div>
                    <Button onClick={handleSave}>
                      <Save className="w-4 h-4 mr-2" />
                      保存更改
                    </Button>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>
        </div>
      </main>
    </div>
  )
}
